package s63.kong.shop.modules.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import s63.kong.shop.pojo.Menu;
import s63.kong.shop.pojo.Role;
import s63.kong.shop.pojo.User;
import s63.kong.shop.service.MenuService;
import s63.kong.shop.service.RoleService;
import s63.kong.shop.service.UserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名查询用户对象
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, username));
        if (user==null) throw new UsernameNotFoundException("用户不存在");

        //2.根据用户Id查询用户对应的角色
        List<Role> roleList = roleService.listByUserId(user.getUserId());
        //3.根据用户Id查询用户对应的权限
        List<Menu> menuList = menuService.listByUserId(user.getUserId());

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setRoleKeyList(roleList.stream().map(Role::getRoleKey).collect(Collectors.toList()));
//        loginUser.setPermsList(menuList.stream().map(Menu::getPerms).collect(Collectors.toList()));
        loginUser.setPermsList(menuList.stream().filter(menu -> StringUtils.hasText(menu.getPerms())).map(Menu::getPerms).collect(Collectors.toList()));
        return loginUser;
    }
}
